<?php
include_once('../db/constants.php');

error_reporting(E_ALL);

define("IMG_WIDTH", 1200);
define("IMG_HEIGHT", 630);
define("HORIZONTAL_MARGIN", 150);
define("VERTICAL_MARGIN", 200);
define("LINES_SEPARATION", 60);	// Percentage
define("MAX_FONT", 45);
define("MIN_FONT", 10);
define("FONT_STEP", 1.5);
define("BREAK_LINE_TOLERANCE", 15);		// Percentage
define("BREAK_BY", "<br />");

define("CATEGORY_SIZE", 37);
define("CATEGORY_OFFSET", 600);

// File acording to index.php path
define("FONT_FILE", './imageGenerator/verdana.ttf');


$backgroundColors = array(  array('153', '0', '51'), 
							array('102', '153', '0'),
							array('0', '153', '255'),
							array('0', '51', '204'),
							array('241', '146', '26')
);

function generateImage($textToPrint, $category, $fileName) {
	global $backgroundColors;

	// Create the image
	$im = imagecreatetruecolor(IMG_WIDTH, IMG_HEIGHT);
	$RGBToUse = $backgroundColors[ rand( 0, count($backgroundColors) - 1) ];
	$backgroundColor = imagecolorallocate($im, $RGBToUse[0], $RGBToUse[1], $RGBToUse[2]);
	imagefill($im, 0, 0, $backgroundColor);
	$color = imagecolorallocate($im, '255', '255', '255');

	$lines = separateLines($textToPrint);

	$fontSize = MAX_FONT;
	$linesBreaked = breakLongLines($lines, $fontSize);
	$linesFit = linesFitHeight(count($linesBreaked), $fontSize);
	while( ($linesBreaked == null || $linesFit == false) && $fontSize > MIN_FONT) {
		$fontSize = $fontSize - FONT_STEP;
		$linesBreaked = breakLongLines($lines, $fontSize);
		$linesFit = linesFitHeight(count($linesBreaked), $fontSize);
	}

	printLinesCentered($im, $color, $linesBreaked, $fontSize);
	printCategory($im, $category);

	imagepng($im, $fileName);
	imagedestroy($im);
}

function printCategory($im, $category) {
	$color = imagecolorallocate($im, '255', '255', '255');

	$xPos = (IMG_WIDTH - getTextWidth(CATEGORY_SIZE, FONT_FILE, $category))/2;
	
	imagettftext($im, CATEGORY_SIZE, 0, $xPos, CATEGORY_OFFSET, $color, FONT_FILE, $category);
}

function printLinesCentered($im, $color, $lines, $fontSize) {
	$linesHeight = getTextHeight($fontSize, FONT_FILE);
	$Ymargin = getYMargin(count($lines), $fontSize);

	for ($i = 0; $i < count($lines); $i++) {
		$xPos = (IMG_WIDTH - getTextWidth($fontSize, FONT_FILE, $lines[$i]))/2;
		$yPos = $Ymargin/2 + $linesHeight + $i*($linesHeight + ($linesHeight*LINES_SEPARATION)/100);

		imagettftext($im, $fontSize, 0, $xPos, $yPos, $color, FONT_FILE, $lines[$i]);
	}
}

function breakLongLines($lines, $fontSize) {
	// Return null if the result doesn't fit in the screen
	$breakedLines = array();

	if (count($lines) == 1) {
		$margins = IMG_WIDTH - getTextWidth($fontSize, FONT_FILE, $lines[0]);
		// Discount the tolerated porcentage to the size, if that size works returns null 
		// to reduce sizes, trying to fit all in one line.
		$marginTolerated = IMG_WIDTH - getTextWidth($fontSize, FONT_FILE, $lines[0])*(100-BREAK_LINE_TOLERANCE)/100;

		if ($margins > HORIZONTAL_MARGIN) {
			return $lines;
		} else if ($marginTolerated > HORIZONTAL_MARGIN) {
			return null;
		}
	}

	for ($i = 0; $i < count($lines); $i++) {
		$currentLine = $lines[$i];

		$textWidth = getTextWidth($fontSize, FONT_FILE, $currentLine);
		$margins = IMG_WIDTH - $textWidth;

		if ($margins < HORIZONTAL_MARGIN) {
			$amountParts = ceil($textWidth/(IMG_WIDTH - HORIZONTAL_MARGIN));
			$breakedLinesPartial = getBreakedLines($currentLine, $amountParts);

			for ($j = 0; $j < count($breakedLinesPartial); $j++) { 
				array_push($breakedLines, $breakedLinesPartial[$j]);
			}
		} else {
			array_push($breakedLines, $currentLine);
		}
	}
	
	return $breakedLines;
}

function linesFitHeight($amountLines, $fontSize) {
	$Ymargin = getYMargin($amountLines, $fontSize);

	return ($Ymargin > VERTICAL_MARGIN);
}

function getBreakedLines($line, $amountParts) {
	if ($amountParts == 1)
		return $line;

	$amountLettersPerPart = strlen($line)/$amountParts;
	$invertedLine = strrev($line);
	$breakedLines = array();

	$prevIndex = 0;
	for($i = 0; $i < $amountParts - 1; $i++) {
		$indexIdealBreak = $amountLettersPerPart*($i + 1);
		$spaceForward = stripos($line, " ", $indexIdealBreak);
		$spaceBackward = strlen($invertedLine) - stripos($invertedLine, " ", strlen($invertedLine) - $indexIdealBreak);

		$distanceForward = abs($indexIdealBreak - $spaceForward);
		$distanceBackward = abs($indexIdealBreak - $spaceBackward);
		$index = ($distanceForward < $distanceBackward) ? $spaceForward : $spaceBackward;

		array_push($breakedLines, substr($line, $prevIndex, $index - $prevIndex));
		$prevIndex = $index;
	}

	array_push($breakedLines, substr($line, $prevIndex));
	
	return $breakedLines;
}

function separateLines($completeText) {
	$parcialText = $completeText;
	$lines = array();

	$prev = 0;
	$index = stripos($parcialText, BREAK_BY);
	while ($index) {
		array_push($lines, substr($parcialText, $prev, $index - $prev));
		$prev = $index + strlen(BREAK_BY);
		$index = stripos($parcialText, BREAK_BY, $prev);
	}

	if (substr($parcialText, $prev) != null && substr($parcialText, $prev) != "")
		array_push($lines, substr($parcialText, $prev));

	return $lines;
}

function getBiggestLineIndex($lines) {
	$biggestIndex = 0;
	$biggestValue = 0;

	for($i = 0; $i < count($lines); $i++) {
		if ($biggestValue < strlen($lines[$i])) {
			$biggestValue = strlen($lines[$i]);
			$biggestIndex = $i;
		}
	}

	return $biggestIndex;
}

function getTextWidth($size, $fontfile, $text) {
	$corners = imagettfbbox($size, 0, $fontfile, $text);

	return abs($corners[4] - $corners[0]);
}

function getTextHeight($size, $fontfile) {
	$corners = imagettfbbox($size, 0, $fontfile, "Foo");

	return abs($corners[5] - $corners[1]);
}

function getYMargin($amountLines, $fontSize) {
	$linesHeight = getTextHeight($fontSize, FONT_FILE);

	$lowestY = $amountLines*($linesHeight + ($linesHeight*LINES_SEPARATION)/100);
	return IMG_HEIGHT - $lowestY;
}

?>

<html>
<head>
</head>
<body>
</body>
</html>


